<?php

namespace App\Http\Controllers\Backend;

use App\Models\User;
use App\Service\Tree;
use App\Models\SiteCate;

class SiteCateController extends BaseController
{
    protected $channel;

    // 栏目管理
    public function initialize()
    {
        parent::initialize();

        $this->model = 'SiteCate';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 返回列表数据
    public function _lists()
    {
        $where = $this->listWhere();
        $model = new SiteCate();

        // 查询（列表展示）
        /*$page = $this->page;
        $rows = $this->rows;
        if($where){
            $result = $model->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->isCache(true)->listPage($where, $page, $rows, "id DESC");
        }*/
        $lists = $model->isCache(true)->getAll($where, 'rank ASC');
        $lists = is_object($lists) ? $lists->toArray() : $lists;

        if($lists){
            // 选择的用户信息 uid
            $uids   = array_column($lists, 'uid');
            $userDb = new User();
            $users  = $userDb->isCache(true)->getListInIds($uids);
            $types  = $this->userType(); // 认证类型
            foreach($users as &$user){
                // 组合
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
            }
            foreach($lists as $key => $item){
                $lists[$key]['user'] = $users[$item['uid']] ?? [];
            }

            // 树状制作
            $tree  = new Tree();
            $lists = $tree->toTree($lists); // 树状
        }
        $total  = count($lists);
        $result = ['total' => $total, 'page' => 1, 'rows' => $this->rows, 'list' => $lists,];

        return $this->success($result);
    }

    // 返回列表数据
    public function lists()
    {
        $where = $this->listWhere();
        $page  = $this->page;
        $rows  = $this->rows;
        $model = new SiteCate();
        if($model === false){
            return $this->error($this->error);
        }

        // 模型 和 查询
        if($where){
            $result = $model->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->isCache(true)->listPage($where, $page, $rows, "id DESC");
        }
        if($result['list']){
            // 选择的用户信息 uid
            $uids   = array_column($result['list'], 'uid');
            $userDb = new User();
            $users  = $userDb->isCache(true)->getListInIds($uids);
            $types  = $this->userType(); // 认证类型
            foreach($users as &$user){
                // 组合
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
            }
            foreach($result['list'] as $key => $item){
                $result['list'][$key]['user'] = $users[$item['uid']] ?? [];
            }
        }

        return $this->success($result);
    }

    // 查找
    public function show()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');

        $where = ['id' => $this->id];
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());

        // 选择的用户信息 uid
        $info = is_object($info) ? $info->toArray() : $info;
        if($info['uid']){
            $userDb = new User();
            $user   = $userDb->isCache(true)->getOneById($info['uid']);
            if($user){
                $types = $this->userType(); // 认证类型
                // 组合
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
            }

            // 组合
            $info['user'] = $user;
        }

        return $this->success($info);
    }


    // 排序
    public function rank()
    {
        $_value = $this->getData('rank', 0, 'intval');
        $this->throwIf(is_null($_value), '请填写排序数字！');

        return $this->changeField('rank', $_value);
    }

    // 启用禁用
    public function status()
    {
        $_value = $this->getData('status', null, 'intval');
        $this->throwIf(is_null($_value), '是否启用状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1]), '是否启用状态必须为0或1！');

        return $this->changeField('status', $_value);
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        // 删除的时候：如果有子级不能删除
        if(!empty($data['pid'])){
            $cateDb = new SiteCate();
            $ids    = $cateDb->getChildIds($this->id);
            $this->throwIf($ids, '有子级不能被删除！');
        }

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['status' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表查询
    protected function listWhere()
    {
        $where   = [['status', '>=', 0]];
        $keyword = $this->getData('keyword', null, 'trim');
        if($keyword){
            $where[] = $this->orWhere('title|keyword|description', 'like', $keyword);
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            //'id'          => $this->getData("id", 0, 'intval'),
            'rank'        => $this->getData("rank", 0, 'intval'),
            'title'       => $this->getData("title", '', 'trim'),
            'pid'         => $this->getData("pid", 0, 'intval'),
            'status'      => $this->getData("status", 1, 'intval'),
            'uid'         => $this->getData("uid", 0, 'intval'),
            'keyword'     => $this->getData("keyword", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            //'ctime'       => $this->getData("ctime", 0, 'intval'),
            //'mtime'       => $this->getData("mtime", 0, 'intval'),
        ];

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            //'id'          => $this->getData("id", 0, 'intval'),
            'rank'        => $this->getData("rank", 0, 'intval'),
            'title'       => $this->getData("title", '', 'trim'),
            'pid'         => $this->getData("pid", 0, 'intval'),
            'status'      => $this->getData("status", 1, 'intval'),
            'uid'         => $this->getData("uid", 0, 'intval'),
            'keyword'     => $this->getData("keyword", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            //'ctime'       => $this->getData("ctime", 0, 'intval'),
            //'mtime'       => $this->getData("mtime", 0, 'intval'),
        ];

        // 修改的时候：如果有父级 则父级不能是当前id 也不能是当前id的子级
        if(!empty($data['pid'])){
            $pid = $data['pid'];
            $id  = $this->id;
            $this->throwIf(empty($id), '请指定要修改的记录！');
            $this->throwIf($id == $pid, '修改父级不能是自己！');
            // 获取当前的子级
            $cateDb = new SiteCate();
            $ids    = $cateDb->getChildIds($id);
            $this->throwIf($ids && in_array($pid, $ids), '修改父级不能是自己的子级！');
        }

        return $data;
    }

}


